<template>
  <Form ref="target" :validation-schema="schema" v-slot="{ errors }">
    <Field
      v-model="formData.mobile"
      name="mobile"
      type="text"
      placeholder="请输入手机号"
      :class="{ error: errors.mobile }"
    />
    <!-- 约定显示校验错误结果 -->
    <div class="error" v-if="errors.mobile">{{ errors.mobile }}</div>
    <Field
      v-model="formData.password"
      name="password"
      type="password"
      placeholder="请输入密码"
      :class="{ error: errors.password }"
    />
    <div class="error" v-if="errors.password">{{ errors.password }}</div>
    <button @click="submit">登录</button>
  </Form>
</template>

<script>
import { ref } from 'vue'
import { Form, Field } from 'vee-validate'
export default {
  components: {
    Form,
    Field
  },
  setup() {
    const formData = {
      mobile: 13567899987,
      password: 121212
    }
    const schema = {
      mobile(value) {
        if (!value) return '请输入手机号'
        if (!/^1[3-9]\d{9}$/.test(value)) return '手机格式错误'
        return true
      },
      password(value) {
        if (!value) return '请输入密码'
        if (!/\d{6}$/.test(value)) return '密码格式错误'
        return true
      }
    }
    const target = ref(null) // 定义引用属性 <Form ref="target"
    const submit = () => {
      // Form 组件提供了一个 validate 函数作为整体表单校验，返回的是一个promise
      target.value.validate().then(res => {
        console.log('表单校验结果', res)
      })
    }
    return { formData, schema, submit, target }
  }
}
</script>

<style></style>
